//
//  YHGradRegistraVC.m
//  ZHZtest
//
//  Created by 李彦宏 on 2018/1/15.
//  Copyright © 2018年 LYH. All rights reserved.
//

#import "YHGradRegistraVC.h"

#import "YHGradRegistraCell.h"//注册cell
#import  "GraduateModel.h" //研究生注册S model
#import "JWGRUsermodel.h"//研究生资料信息model
#import "JWUserManager.h"//研究生资料管理类
#import "BRPickerView.h" //选择器
#import "UITextField+Limit.h"


#define YHGradRegistraCellID @"YHGradRegistraCell"
@interface YHGradRegistraVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIGestureRecognizerDelegate>
@property (nonatomic, strong) UITableView *YHGradRegistraTab;
@property (nonatomic, strong) NSMutableArray *GraduateArry;
@property (nonatomic, strong) UITextField  * TextFiled;
@property (nonatomic, strong) JWGRUsermodel *model;


//注册数据项
@property (nonatomic, strong) NSString *GRneme;//研究生姓名
@property (nonatomic, strong) NSString *GRphone;//研究生电话
@property (nonatomic, strong) NSString *GRpassword;//研究生密码
@property (nonatomic, strong) NSString *GRAdrss;//研究生地址
@property (nonatomic, strong) NSString *GRqq;//研究生QQ
@property (nonatomic, strong) NSString *GRweChat;//研究生微信
@property (nonatomic, strong) NSString *GRjieshu;//研究生时届数
@property (nonatomic, strong) NSString *GRCollge;//学院专业
@property (nonatomic, strong) NSString *GRBirthday;//研究生生日
@property (nonatomic, strong) NSString *GRPayWhy;//打款方式
@property (nonatomic, strong) NSString *GRPayNumber;//打款帐号
@property (nonatomic, strong) NSString *GRRead;//研究生成绩




@end

@implementation YHGradRegistraVC

/**
 *  研究生S 数据的懒加载
 */
- (NSMutableArray *)GraduateArry
{
    if (_GraduateArry == nil) {
        // 初始化
        // 1.获得plist的全路径
        NSString *path = [[NSBundle mainBundle] pathForResource:@"JWGraduateList.plist" ofType:nil];
        
        // 2.加载数组
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
        
        // 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
        NSMutableArray *tgArray = [NSMutableArray array];
        for (NSDictionary *dict in dictArray) {
            // 3.1.创建模型对象
            GraduateModel *tg = [GraduateModel GraduatewithDict:dict];
            
            // 3.2.添加模型对象到数组中
            [tgArray addObject:tg];
        }
        
        // 4.赋值
        _GraduateArry = tgArray;
    }
    return _GraduateArry;
}
//UItableView初始化
- (void)setupTable
{
    UITableView *tableView=[[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    //隐藏组距导航栏的间距
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    tableView.backgroundColor=[UIColor whiteColor];
    tableView.showsHorizontalScrollIndicator=NO;
    tableView.showsVerticalScrollIndicator=NO;
    tableView.dataSource=self;
    tableView.delegate=self;
    tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:tableView];
    self.YHGradRegistraTab=tableView;
    
    [tableView registerNib:[UINib nibWithNibName:@"YHGradRegistraCell" bundle:nil] forCellReuseIdentifier:YHGradRegistraCellID];
    
    //    [tableView registerNib:[UINib nibWithNibName:@"HomeNearbyShopView" bundle:nil] forHeaderFooterViewReuseIdentifier:HomeNearbyShopViewID];
}
- (void)viewDidLoad {
    [super viewDidLoad];
     self.model=[JWUserManager Gme];
    [self setupTable];
    
    // Do any additional setup after loading the view.
}
#pragma -mark -----------------------------tableview datasource and delegate---------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.GraduateArry.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row=indexPath.row;
    YHGradRegistraCell *cell = [tableView dequeueReusableCellWithIdentifier:YHGradRegistraCellID];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    GraduateModel *Ginfo=_GraduateArry[row];
    cell.Gicon.image=[UIImage imageNamed:Ginfo.image];
    cell.GinfoLeb.text=Ginfo.listtext;
    cell.GRtextField.delegate=self;
    cell.GRtextField.tag=row;
    cell.GRtextField.returnKeyType=UIReturnKeyDone;
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImgAction:)];
    tap.numberOfTouchesRequired=1;//手指数
    tap.numberOfTapsRequired=1;//tap次数
    tap.delegate=self;
    if(indexPath.row==5){
        cell.GRtextField.text=self.GRjieshu;
    [cell.GRtextField addGestureRecognizer:tap];
    }
    
    [cell.GRtextField addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    return cell;
}
- (void)textFieldWithText:(UITextField *)textField
{
   
    switch (textField.tag) {
        case 0:
            self.GRneme=textField.text;
            break;
        case 1:
            self.GRphone = textField.text;
            [textField setLimitTextLength:11];
             break;
      
        case 2:
            self.GRAdrss = textField.text;
            break;
        case 3:
            self.GRqq = textField.text;
            break;
        case 4:
            self.GRweChat = textField.text;
            break;
        case 5:
//            self.GRjieshu = textField.text;
            break;
        case 6:
            self.GRCollge = textField.text;
            break;
        case 7:
            self.GRBirthday = textField.text;
            break;

        case 8:
            self.GRPayWhy = textField.text;
            break;
        case 9:
            self.GRPayNumber = textField.text;
            break;
        case 10:
            self.GRRead = textField.text;
            break;
        default:
            break;
    }
}
-(void )tapImgAction:(UITapGestureRecognizer *)send{
    //结束控制器View的编辑状态 退出键盘
     [self.view endEditing:YES];
    __weak typeof(self) weakslf = self;
    [BRStringPickerView showStringPickerWithTitle:@"届数" dataSource:@[@"18", @"19", @"20", @"21", @"22", @"23"] defaultSelValue:@"20" isAutoSelect:YES resultBlock:^(id selectValue) {
        weakslf.GRjieshu = selectValue;
        [weakslf.YHGradRegistraTab reloadData];
    }];

    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.YHGradRegistraTab deselectRowAtIndexPath:indexPath animated:YES];

    
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30;
}



#pragma -mark 尾部的内容
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
        UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_width, 30)];
        footer.backgroundColor=dominantColor;
    UIButton *savebtn=[[UIButton alloc]init];
    savebtn.frame=CGRectMake(20, 0, Screen_width-20, 30);
    [savebtn setTitle:@"注册" forState:UIControlStateNormal];
    savebtn.titleLabel.textAlignment=NSTextAlignmentCenter;
    savebtn.titleLabel.font=[UIFont systemFontOfSize:20];

    [savebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
//savebtn.enabled=_GRqq.length&&_GRneme.length&&_GRphone&&_GRpassword;
    [savebtn addTarget:self action:@selector(SaveBtAc:) forControlEvents:UIControlEventTouchUpInside];
   
    [footer addSubview:savebtn];
    
        return footer;

}


//注册按钮事件
-(void)SaveBtAc:(UIButton *)send{
    
    if (self.GRAdrss==nil){
        self.GRAdrss=@" ";
    }
    if (self.GRqq==nil){
        self.GRqq=@" ";
    }if (self.GRweChat==nil){
        self.GRweChat=@" ";
    }
     if (self.GRjieshu==nil){
        self.GRjieshu=@"";
    }
    if (self.GRCollge==nil){
        self.GRCollge=@" ";
    }
    if (self.GRBirthday==nil){
        self.GRBirthday=@" ";
    }
    if (self.GRPayWhy==nil){
        self.GRPayWhy=@" ";
    }
    if (self.GRPayNumber==nil){
        self.GRPayNumber=@" ";
    }if (self.GRRead==nil){
        self.GRRead=@" ";
    }
    
    if(self.GRneme==nil || self.GRphone==nil){
        [MBProgressHUD showError:@"姓名电话必填！"];
    }else{
        
        NSLog(@">a>%@", self.GRqq);
        [MBProgressHUD showMessage:@"正在注册中....."];
        // 几秒后消失,当前，这里可以改为网络请求
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            BOOL isTel = [self validateMobile:self.GRphone];
            if (isTel == YES) {
                NSDictionary *dict = @{
                                       @"jwid" : JWid,
                                       @"jwpassword" :JWpassword,
                                       @"name" : self.GRneme,
                                       @"phone" : self.GRphone,
                                       @"pass" : @"123456",
                                       @"address" : self.GRAdrss,
                                       @"qnumber" : self.GRqq,
                                       @"wnumber" : self.GRweChat,
                                       @"jieshu" : self.GRjieshu,
                                       @"college" : self.GRCollge,
                                       @"birthday" : self.GRBirthday,
                                       @"moneyway" : self.GRPayWhy,
                                       @"moneynumber":self.GRPayNumber,
                                       @"achievement" : self.GRRead,
                                       };
                NSLog(@"--dict--%@", dict);
                
                [[AFNetworkTool shareManager]postJSONWithUrl:Grduat_Registra parmas:dict successData:^(id json) {
                    //          NSLog(@"-注册-json--%@", json);
                    self.model=[JWGRUsermodel yy_modelWithJSON:json];
                    [JWUserManager saveGR:self.model];
                    
                    if ([json[@"message"] isEqualToString:@"注册成功"]) {
                        // 提示
                        [MBProgressHUD showSuccess:self.model.message];
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }else{
                        [MBProgressHUD showError:self.model.message];
                    }
                } failure:^(NSError *error) {
                    NSLog(@"--error--%@", error);
                }];
                
            }else{
                [Utility showFail:@"电话格式不对"];
            }
            
            // 移除HUD
            [MBProgressHUD hideHUD];
        });
        
        
    }
    
}
- (BOOL)validateMobile:(NSString *)mobile
{
    // 手机号以13、15、18、17开头，八个 \d 数字字符
    NSString * phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0,0-9]))\\d{8}$";
    NSPredicate * phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
